# -*- coding: UTF-8 -*-

import re
import math

_re_param = re.compile('\(([^\)]+)\)')

def extract_param(text):
	match = _re_param.match(text)
	if match == None:
		return
	params = match.group(1).split(',')
	for i in xrange(len(params)):
		params[i] = params[i].strip()
	return params

# convert single color value
# possible : 
#	10			- means 10 in 255
#	20%			- means 20% of 255
#
def color_val(val):
	if val.endswith('%'):
		val = val[:-1]
		try:
			val = float(val) / 100.0
		except ValueError:
			return None
		return int( math.ceil(255 * val) )
	else:
		try:
			return int(val)
		except ValueError:
			return None

# make color parameters
def color_param(text):
	params = extract_param(attr[3:])
	if params == None:
		return None
	if len(params) == 1:
		params = [ params[0] , params[0] , params[0] ]
	elif len(params) != 3:
		return None
	for i in xrange(len(params)):
		params[i] = color_val(params[i])
	return params

def _to_int( cc ):
	MAP = { 'a':10 , 'b':11 , 'c':12 , 'd':13 , 'e':14 , 'f':15 }
	if cc in MAP:
		return MAP[cc]
	else:
		return int(cc)

def cvthex( input ):
	ss = input.lower()
	val = 0
	base = 1
	for i in xrange( len(ss) ):
		c = _to_int( ss[ len(ss) - i - 1 ] )
		val += base*c
		base *= 16
	return val

def gen_color3( ss ):
	if len(ss) < 6:
		for i in xrange( len(ss) , 0 ):
			ss = '0' + ss
	return ( cvthex(ss[0:2]) , cvthex(ss[2:4]) , cvthex(ss[4:6]) )

def gen_color4( ss ):
	if len(ss) < 8:
		for i in xrange( len(ss) , 0 ):
			ss = '0' + ss
	return ( cvthex(ss[0:2]) , cvthex(ss[2:4]) , cvthex(ss[4:6]) , cvthex(ss[6:8]) )

# convert style sheet's color
def convert_color(attr):
	# turn to color
	if attr.startswith('#'):
		val = attr[1:]
		# expand RGB
		l = len(val)
		if l == 1:
			val = '0'+val[0]+'0'+val[0]+'0'+val[0]
		elif l == 3:
			val = val[0]+val[0]+val[1]+val[1]+val[2]+val[2]
		elif not l in (6,8):
			raise ValueError , "Invalid color value."
		# cast to value
		try:
			if len(val) == 6:
				val = gen_color3(val)
			else:
				val = gen_color4(val)
		except ValueError:
			raise ValueError , "Invalid color value."
		return val

	# color conversion
	elif attr.startswith("rgb"):
		params = color_param(attr[3:])
		if params == None:
			raise ValueError , "Invalid color value."
	elif attr.startswith("hls"):
		params = color_param(attr[3:])
		if params == None:
			raise ValueError , "Invalid color value."
	elif attr.startswith("hsv"):
		params = color_param(attr[3:])
		if params == None:
			raise ValueError , "Invalid color value."
	else:
		# find from color table
		raise ValueError , "Invalid color value."
